<%@ Page Language="c#" ContentType="text/html" ResponseEncoding="utf-8" %>
<%@ Import Namespace="ACM.cmsarea08" %>
<%@ Import Namespace="System.Drawing" %>
<%@ Import Namespace="System.Drawing.Drawing2D" %>
<script runat="server">
	const string filePath = "/public/tinyimg";
	const string validExt = ".jpg,.gif,.png";
	
	string currentOp = "";
	
	void Page_Load(object o, EventArgs e) {
		if(Request.Params["op"]!=null) {
			currentOp = Request.Params["op"].ToString();
		}
		
		if(currentOp=="list")
			ReturnFileList();
		if(currentOp=="del") {
			string iddel ="";
			if(Request.Params["id"]==null) {
				Response.Write("NO");
				return;
			}
			iddel = Request.Params["id"].ToString();
			DeleteFile(iddel);
			return;
		}
		if(currentOp=="view") {
			string iddel ="";
			if(Request.Params["id"]==null) {
				Response.Write("NO");
				return;
			}
			iddel = Request.Params["id"].ToString();
			viewFile(iddel);
			return;
		}
		if(currentOp=="save") {
			string iddel ="";
			if(Request.Params["id"]==null) {
				Response.Write("NO");
				return;
			}
			iddel = Request.Params["id"].ToString();
			saveFile(iddel);
			return;
		}		
	}
	
	void ReturnFileList() {
		System.IO.DirectoryInfo di = new System.IO.DirectoryInfo(Server.MapPath(filePath));
		if(di==null) return;
		string files = ("[");
		foreach(System.IO.FileInfo fi in di.GetFiles()) {
			files+=("['" + fi.Name + "','"+filePath + "/"+fi.Name+"'],");
		}
		files = files.Substring(0,files.Length-1) + "]";
		Response.Write(files);
		di=null;
	}
	void DeleteFile(string file) {
		if(!System.IO.File.Exists( Server.MapPath(file) ) ) {
			Response.Write("NO");
			return;
		}
		System.IO.File.Delete(Server.MapPath(file));
		Response.Write("OK");
		return ;
	}	
	
	void viewFile(string guid) {
            string fileName = "";
            byte[] filedati;	
	
		ACM.cmsarea08.Function.CacheFileObjectInfo imageInfo = ACM.cmsarea08.Function.CacheManager.cachemanager.getCacheFileObjectInfo(HttpContext.Current,guid);
		if(imageInfo.exists==false || imageInfo.filename.Trim().Length==0) {
			Nulla(HttpContext.Current,"NO IMG" + 
				 imageInfo.filename + ", " +
				 imageInfo.filesize + ", " +
				 imageInfo.edited + ", " +            	     
				 imageInfo.exists 
				 );
				 return;
		}
		string fileStream = ACM.cmsarea08.Function.CacheManager.cachemanager.getCacheFileObject(HttpContext.Current,guid);
		if(string.IsNullOrEmpty(fileStream) || fileStream.IndexOf("#")==-1 ) {
			Nulla(HttpContext.Current,"NO VALID STREAM"); return;            	
		}
		
		filedati = Convert.FromBase64String(fileStream.Substring(fileStream.IndexOf("#")+1));
		fileName = imageInfo.filename; 		
	   /* leggo i size dell'image */
		if (fileName.Trim() == "") { Nulla(HttpContext.Current); return; }
		if (filedati == null) { Nulla(HttpContext.Current); return; }
		if (fileName.Trim().IndexOf('.') == -1) { Nulla(HttpContext.Current); return; }
		
		string ext = fileName.Trim().Substring(fileName.Trim().LastIndexOf('.') );
		LoadIMAGE(HttpContext.Current,filedati, ext.ToLower(),75,75,guid,fileName.Trim());
	}
	
		private void Nulla(HttpContext corrente) { 
            corrente.ApplicationInstance.Response.StatusCode = 404;
            corrente.ApplicationInstance.CompleteRequest();
		}			
		private void Nulla(HttpContext corrente, string errore) { 
        	//HttpContext.Current.Response.Clear();
        	corrente.Response.ContentType = "text/html";
        	corrente.Response.Write(errore);
            corrente.Response.End();
		}	
        private void LoadIMAGE(HttpContext corrente,byte[] data,string extension,int w, int h,string chiave,string filename)
        {
            try
            {
                if (data.Length == 0)
                {
                	Nulla(corrente,"NIENTE");
                    //nulla("no dati byte[]");
                    return;
                }
                System.IO.MemoryStream mr = new System.IO.MemoryStream(data);
                
                System.Drawing.Image im = System.Drawing.Image.FromStream(mr,true);
                if (im == null) { Nulla(corrente,"NIENTE"); 
                	return; }
                if(w==0)
                	w = im.Width;
                if(h==0)
                	h = im.Height;
                
                decimal wnew = 0;
                decimal hnew = 0;
                decimal cwnew = 0;
                decimal chnew = 0;                
                decimal scale = 0;
                int scaleby = -1;
                if(w<0) 
                	scaleby = 1;
                else if (h<0)
                	scaleby = 2;
                else
                	scaleby=0;
                
                if(scaleby>0) {
                	scale = ((decimal)im.Width / (decimal)im.Height);
                	if(scaleby == 1) {
                		chnew = hnew = h;
                		cwnew = wnew = (decimal) h*scale;
                	}
                	if(scaleby == 2) {
                		chnew = hnew = (decimal) w/scale;
                		cwnew = wnew = w;
                	}                	
                } else {
                	cwnew = wnew = w;
                	chnew = hnew = h;
                }
                
                //se le dime sono maggiori di cwnew e chnew:
                
                if(im.Height> chnew || im.Width>cwnew) {
                	//scala comunque:
//                	scale = 
//                		(im.Width>=im.Height ? (
//                			((decimal)im.Width/(decimal)im.Height) ) :
//                		 ( ((decimal)im.Height/(decimal)im.Width)  ) );
			scale = ((decimal)im.Width/(decimal)im.Height) ;

                	if(im.Height>im.Width) {
						wnew =   (scale<1?((decimal)h*scale):((decimal)h/scale));
						hnew =   h;
                	} else {
						wnew =   w;
						hnew =   (scale<1?((decimal)w*scale):((decimal)w/scale));
                	}
                } else {
                	hnew = im.Height;
                	wnew = im.Width;
                }
                
                
                System.Drawing.Image oImage = new Bitmap((int)wnew,(int)hnew,im.PixelFormat);
                Graphics ograp = Graphics.FromImage(oImage);
                ograp.Clear(Color.White);
                ograp.CompositingQuality = CompositingQuality.HighQuality;
                ograp.SmoothingMode = SmoothingMode.HighQuality;
                ograp.InterpolationMode = InterpolationMode.HighQualityBicubic;
                
//                int posX = 0;
//                int posY = 0;
//                posX = (int)(cwnew/(decimal)2 - wnew/(decimal)2);
//                posY = (int)(chnew/(decimal)2 - hnew/(decimal)2);
                Rectangle orec = new Rectangle(0,0,(int)wnew,(int)hnew);
                ograp.DrawImage(im,orec);
                //System.Drawing.Image low = im.GetThumbnailImage((int)wnew, (int)hnew, null, IntPtr.Zero);
                //HttpContext.Current.Response.ContentType = "image/jpeg";
                
                switch (extension)
                {
                    case ".gif":
                        corrente.Response.ContentType = "image/gif";
                        break;
                    case ".jpg":
                        corrente.Response.ContentType = "image/jpeg";
                        break;
                    case ".png":
                        corrente.Response.ContentType = "image/png";
                        break;
                    default:
                        throw new NotSupportedException("Unrecognized image type.");
                } 
                
                oImage.Save(corrente.Response.OutputStream, System.Drawing.Imaging.ImageFormat.Jpeg);
                corrente.Response.End();
                //low.Dispose();
                oImage.Dispose();
                im.Dispose();
                mr.Close();
            }
            catch (Exception ex)
            {
                //non renderizzo nulla.
                Nulla(corrente,ex.ToString());
            }
        }
		
	void saveFile(string guid) {
            string fileName = "";
            byte[] filedati;	
	
		ACM.cmsarea08.Function.CacheFileObjectInfo imageInfo = ACM.cmsarea08.Function.CacheManager.cachemanager.getCacheFileObjectInfo(HttpContext.Current,guid);
		if(imageInfo.exists==false || imageInfo.filename.Trim().Length==0) {
			Response.Write("NO EXISTS");
		    return;
		}
		string fileStream = ACM.cmsarea08.Function.CacheManager.cachemanager.getCacheFileObject(HttpContext.Current,guid);
		if(string.IsNullOrEmpty(fileStream) || fileStream.IndexOf("#")==-1 ) {
			Response.Write("NO STREAM");
		    return;
		}
		
		filedati = Convert.FromBase64String(fileStream.Substring(fileStream.IndexOf("#")+1));
		fileName = imageInfo.filename; 		
	   /* leggo i size dell'image */
		if (fileName.Trim() == "") { 			
			Response.Write("NO NAME");
		    return;
		}
		if (filedati == null) { 
			Response.Write("NO DATA");
		    return;
		}
		int filecont = 1;
		bool found = true;
		string saveFile = Server.MapPath(filePath + "/") + fileName;
		try {
		if(System.IO.File.Exists( saveFile ) ) {
			//entra nel ciclo con interact.
			string ext = saveFile.Substring(saveFile.LastIndexOf('.'));
			string tempName = saveFile.Substring(0,saveFile.LastIndexOf('.')) + "({0})" + ext;
			while (found==true) {
				saveFile = string.Format(tempName,filecont.ToString());
				if(System.IO.File.Exists( saveFile ) ) {
					filecont++;
				} else {
					found=false;break;
				}
			}
		}		
		using (System.IO.FileStream str = new System.IO.FileStream(saveFile,System.IO.FileMode.Create)) {
			str.Write(filedati,0,filedati.Length);
		}
		} catch (Exception ex) {
			Response.Write(ex.ToString());
			return;
		}
		ACM.cmsarea08.Function.CacheManager.cachemanager.RemoveCacheFileObject(HttpContext.Current,guid);
		Response.Write("OK");
	}
	
</script>
